import { _decorator, Component, Node, Vec3, Label, Color, Widget, UITransform } from 'cc';
import { Clock } from './core/Clock';
import { InputBridge } from './input/InputBridge';
import { AutoAimSystem } from './systems/AutoAimSystem';
import { AutoFireSystem } from './systems/AutoFireSystem';
import { AutoReloadSystem } from './systems/AutoReloadSystem';
import { HUDController } from './hud/HUDController';
import { PlayerController } from './gameplay/PlayerController';
import { EnemyDummy } from './gameplay/EnemyDummy';
import { ExtractPoint } from './gameplay/ExtractPoint';
import { GlobalEventBus } from './core/EventBus';
import { track } from './telemetry/Track';
import { TICK_RATES } from './shared';
import { SceneInstaller } from './installers/SceneInstaller';

const { ccclass, property } = _decorator;

@ccclass('DemoSceneBuilder')
export class DemoSceneBuilder extends Component {
  @property
  public seed = 12345;
  @property
  public useInstaller = true; // 默认使用自动安装器，避免双路径冲突
  private worldRoot: Node | null = null;
  private uiRoot: Node | null = null;

  start() {
    if (this.useInstaller) {
      SceneInstaller.ensure(this.node.scene);
      const payload = { seed: this.seed, map: 'demo' };
      GlobalEventBus.emit('match/start', payload);
      track('match_start', payload);
      return;
    }
    this.bootstrapMatch();
    this.spawnEnemies();
    this.createExtractPoint();
  }

  onDestroy() {
    const payload = { result: 'quit' as const };
    GlobalEventBus.emit('match/end', payload);
    track('match_finish', payload);
  }

  private bootstrapMatch() {
    // Ensure we spawn gameplay under scene root (World) and HUD under Canvas
    const scene = this.node.scene as unknown as Node;
    this.worldRoot = scene;
    this.uiRoot = scene.getChildByName('Canvas') ?? this.node;

    const player = new Node('Player');
    this.worldRoot.addChild(player);

    const clock = player.addComponent(Clock);
    const input = player.addComponent(InputBridge);
    const reload = player.addComponent(AutoReloadSystem);
    const aim = player.addComponent(AutoAimSystem);
    const fire = player.addComponent(AutoFireSystem);
    const controller = player.addComponent(PlayerController);

    aim.clock = clock;
    aim.autoReload = reload;
    aim.aimPivot = player;

    fire.clock = clock;
    fire.autoAim = aim;
    fire.autoReload = reload;

    controller.inputBridge = input;
    controller.autoReload = reload;

    const muzzle = new Node('Muzzle');
    muzzle.setWorldPosition(new Vec3(0, 1.2, 1));
    player.addChild(muzzle);
    fire.muzzle = muzzle;

    const hudNode = new Node('HUD');
    const hud = hudNode.addComponent(HUDController);
    this.uiRoot.addChild(hudNode);
    // Stretch HUD to full Canvas so child Widgets align correctly
    hudNode.addComponent(UITransform);
    const hudStretch = hudNode.addComponent(Widget);
    hudStretch.isAlignLeft = hudStretch.isAlignRight = hudStretch.isAlignTop = hudStretch.isAlignBottom = true;
    hudStretch.left = 0; hudStretch.right = 0; hudStretch.top = 0; hudStretch.bottom = 0;

    // Build minimal HUD labels and wire references for live updates
    const weaponLabelNode = new Node('WeaponLabel');
    const weaponLabel = weaponLabelNode.addComponent(Label);
    weaponLabel.string = 'Weapon: -';
    const w1 = weaponLabelNode.addComponent(Widget);
    w1.isAlignTop = true; w1.isAlignLeft = true; w1.top = 10; w1.left = 10;
    hudNode.addChild(weaponLabelNode);

    const magLabelNode = new Node('MagLabel');
    const magLabel = magLabelNode.addComponent(Label);
    magLabel.string = 'Mag: -';
    const w2 = magLabelNode.addComponent(Widget);
    w2.isAlignTop = true; w2.isAlignLeft = true; w2.top = 40; w2.left = 10;
    hudNode.addChild(magLabelNode);

    const reserveLabelNode = new Node('ReserveLabel');
    const reserveLabel = reserveLabelNode.addComponent(Label);
    reserveLabel.string = 'Reserve: -';
    const w3 = reserveLabelNode.addComponent(Widget);
    w3.isAlignTop = true; w3.isAlignLeft = true; w3.top = 70; w3.left = 10;
    hudNode.addChild(reserveLabelNode);

    const toastLabelNode = new Node('ToastLabel');
    const toastLabel = toastLabelNode.addComponent(Label);
    toastLabel.string = '';
    const w4 = toastLabelNode.addComponent(Widget);
    w4.isAlignTop = true; w4.isAlignHorizontalCenter = true; w4.top = 10;
    hudNode.addChild(toastLabelNode);

    hud.weaponLabel = weaponLabel;
    hud.magazineLabel = magLabel;
    hud.reserveLabel = reserveLabel;
    hud.toastLabel = toastLabel;

    clock.register('demo-ai-log', TICK_RATES.ai, () => {});
    clock.register('demo-nav-log', TICK_RATES.navigation, () => {});
    // Debug label for movement feedback
    const debugNode = new Node('DebugLabel');
    const debugLabel = debugNode.addComponent(Label);
    const dbgWidget = debugNode.addComponent(Widget);
    dbgWidget.isAlignBottom = true; dbgWidget.isAlignLeft = true; dbgWidget.bottom = 10; dbgWidget.left = 10;
    debugLabel.string = 'WASD 移动(调试)';
    hudNode.addChild(debugNode);
    clock.register('demo-stats-log', TICK_RATES.stats, () => {
      const pos = player.worldPosition;
      const mv = input.snapshot().move;
      debugLabel.string = `Pos(${pos.x.toFixed(1)},${pos.z.toFixed(1)}) Move(${mv.x.toFixed(2)},${mv.y.toFixed(2)})`;
    });

    // Spawn point (gameplay world)
    player.setWorldPosition(new Vec3(0, 0, 0));
    // Visual marker for Player
    const pLabel = player.addComponent(Label);
    pLabel.string = 'Player';
    pLabel.color = Color.WHITE;

    const payload = { seed: this.seed, map: 'demo' };
    GlobalEventBus.emit('match/start', payload);
    track('match_start', payload);
  }

  private spawnEnemies() {
    const positions = [
      new Vec3(6, 0, 4),
      new Vec3(-5, 0, 7),
      new Vec3(2, 0, -6),
      new Vec3(8, 0, -3),
    ];
    positions.forEach((pos, index) => {
      const enemyNode = new Node(`Enemy_${index}`);
      enemyNode.setWorldPosition(pos);
      const enemy = enemyNode.addComponent(EnemyDummy);
      enemy.threatLevel = 0.3 + index * 0.15;
      enemy.maxHealth = 80 + index * 20;
      const label = enemyNode.addComponent(Label);
      label.string = 'Enemy';
      label.color = Color.RED;
      (this.worldRoot ?? this.node).addChild(enemyNode);
    });
  }

  private createExtractPoint() {
    const extractNode = new Node('ExtractPoint');
    extractNode.setWorldPosition(new Vec3(12, 0, -8));
    extractNode.addComponent(ExtractPoint);
    (this.worldRoot ?? this.node).addChild(extractNode);
  }
}

// UI marker helper (currently unused)
function createMarker(name: string, color: Color): Node {
  const node = new Node(name);
  const label = node.addComponent(Label);
  label.string = name;
  label.color = color;
  return node;
}

